//
//  File.swift
//  
//
//  Created by 钟志远 on 2021/4/16.
//

import Foundation
import Vapor
import Fluent

extension SchemaBuilder {
    func autoId() -> SchemaBuilder {
        return self.field(.id, .uuid, .custom("default gen_random_uuid()"), .identifier(auto: false))
    }
}

class CreateSwiftPanTable: Migration {
    func prepare(on database: Database) -> EventLoopFuture<Void> {
        return database.schema("user")
//            .id()
            .autoId()
            .field("user_name", .string, .required)
            .unique(on: "user_name")
            .field("password", .string, .required)
            .field("created_at", .datetime)
            .field("updated_at", .datetime)
            .create()
            .flatMap { _ in
                database.schema("user_info")
                    .autoId()
                    .field("nick_name", .string, .required, .custom("default ''"))
                    .field("user_id", .uuid)
                    .unique(on: "user_id")
                    .field("created_at", .datetime)
                    .field("updated_at", .datetime)
                    .create()
            }
            .flatMap { _ in
                database.schema("file_type")
                    .autoId()
                    .field("ext", .string, .required)
                    .field("icon", .string, .required)
                    .create()
            }
            .flatMap { _ in
                database.schema("file")
                    .autoId()
                    .field("parent_id", .uuid)
                    .field("user_id", .uuid, .required)
                    .field("file_type_id", .uuid)
                    .field("is_dir", .bool, .required, .custom("default false"))
                    .field("file_name_real", .string)
                    .field("file_name_show", .string, .required)
                    .field("file_length", .int, .required)
                    .field("created_at", .datetime)
                    .field("updated_at", .datetime)
                    .create()
            }
    }
    
    func revert(on database: Database) -> EventLoopFuture<Void> {
        return database.schema("user").delete()
            .flatMap{ database.schema("user_info").delete()}
            .flatMap{ database.schema("file_type").delete()}
            .flatMap{ database.schema("file").delete()}
    }
}
